package com.example.blogapi.controller;

import com.example.blogapi.model.User;
import com.example.blogapi.service.UserService;
import com.example.blogapi.util.HttpUtil;
import com.example.blogapi.util.JsonUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserController implements HttpHandler {
    private final UserService userService;

    public UserController() {
        this.userService = new UserService();
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();

        try {
            if (method.equals("OPTIONS")) {
                handleOptionsRequest(exchange);
            } else if (method.equals("GET") && path.matches("/api/users/?")) {
                handleGetAllUsers(exchange);
            } else if (method.equals("GET") && path.matches("/api/users/\\d+/?")) {
                handleGetUserById(exchange);
            } else if (method.equals("POST") && path.matches("/api/users/?")) {
                handleCreateUser(exchange);
            } else if (method.equals("PUT") && path.matches("/api/users/\\d+/?")) {
                handleUpdateUser(exchange);
            } else if (method.equals("DELETE") && path.matches("/api/users/\\d+/?")) {
                handleDeleteUser(exchange);
            } else {
                String response = JsonUtil.toJson(Map.of("error", "Not found"));
                HttpUtil.sendResponse(exchange, 404, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 500, response);
        }
    }

    private void handleOptionsRequest(HttpExchange exchange) throws IOException {
        HttpUtil.sendResponse(exchange, 200, "");
    }

    private void handleGetAllUsers(HttpExchange exchange) throws IOException, SQLException {
        List<User> users = userService.getAllUsers();
        String response = JsonUtil.toJson(users);
        HttpUtil.sendResponse(exchange, 200, response);
    }

    private void handleGetUserById(HttpExchange exchange) throws IOException, SQLException {
        Long id = HttpUtil.extractIdFromPath(exchange.getRequestURI().getPath(), "/api/users/(\\d+)/?");
        
        User user = userService.getUserById(id);
        if (user != null) {
            String response = JsonUtil.toJson(user);
            HttpUtil.sendResponse(exchange, 200, response);
        } else {
            String response = JsonUtil.toJson(Map.of("error", "User not found"));
            HttpUtil.sendResponse(exchange, 404, response);
        }
    }

    private void handleCreateUser(HttpExchange exchange) throws IOException, SQLException {
        String requestBody = HttpUtil.getRequestBody(exchange);
        User user = JsonUtil.fromJson(requestBody, User.class);
        
        try {
            User createdUser = userService.createUser(user);
            String response = JsonUtil.toJson(createdUser);
            HttpUtil.sendResponse(exchange, 201, response);
        } catch (IllegalArgumentException e) {
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 400, response);
        }
    }

    private void handleUpdateUser(HttpExchange exchange) throws IOException, SQLException {
        Long id = HttpUtil.extractIdFromPath(exchange.getRequestURI().getPath(), "/api/users/(\\d+)/?");
        String requestBody = HttpUtil.getRequestBody(exchange);
        User user = JsonUtil.fromJson(requestBody, User.class);
        
        try {
            User updatedUser = userService.updateUser(id, user);
            String response = JsonUtil.toJson(updatedUser);
            HttpUtil.sendResponse(exchange, 200, response);
        } catch (IllegalArgumentException e) {
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 400, response);
        }
    }

    private void handleDeleteUser(HttpExchange exchange) throws IOException, SQLException {
        Long id = HttpUtil.extractIdFromPath(exchange.getRequestURI().getPath(), "/api/users/(\\d+)/?");
        
        try {
            boolean deleted = userService.deleteUser(id);
            if (deleted) {
                HttpUtil.sendResponse(exchange, 204, "");
            } else {
                String response = JsonUtil.toJson(Map.of("error", "Failed to delete user"));
                HttpUtil.sendResponse(exchange, 500, response);
            }
        } catch (IllegalArgumentException e) {
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 400, response);
        }
    }
}